//
//  UITableViewController+HDChatLIstController.m
//  app
//
//  Created by D on 15/5/18.
//  Copyright (c) 2015年 hdaren. All rights reserved.
//

#import "HDChatLIstController.h"
#import "HDChatListManager.h"
#import "HDChatListResult.h"
#import "HDChatListCell.h"
#import "HDChatListModel.h"
#import "HDChatOBO.h"
#import "HDChatReply.h"

static const CGFloat kCartTotalPanelHeight = 120;

@interface HDChatLIstController ()<HDChatListCellDelegate>

@property (nonatomic,strong) HDChatListManager * chatListManager;
@property (nonatomic,strong) HDChatListResult * chatListResutl;
@property (nonatomic,strong) UITableView * tableView;

@end


@implementation HDChatLIstController


-(void)viewDidLoad
{
    [super viewDidLoad];
    NSLog(@"%@",self);
    self.title = @"我的客服";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.navigationController.navigationBar.hidden = NO;
    self.tableView = [[UITableView alloc]initWithFrame:CGRectOf(CGPointMake(0, 64),
                                                                [self.view.ubo fw:UB_WIDTH fh:UB_HEIGHT uh:-kCartTotalPanelHeight oh:+56]) style:UITableViewStyleGrouped];
    
    self.tableView.sectionHeaderHeight = 0;
    self.tableView.sectionFooterHeight = 0;
    self.tableView.headerRefreshController = [[UIRefreshHeaderController alloc] initWithTableView:self.tableView caller:[UBTargetCaller of:self action:@selector(refreshData)]];
    self.tableView.nothingRefreshView = [[UIRefreshNotingRefreshView alloc]initWithView:self.tableView viewController:self tryAgain:@selector(refreshData)];
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;

    [self.view addSubview:self.tableView];
    
    self.chatListResutl = [[HDChatListResult alloc]initWithTarget:self action:@selector(chatListLoadData:)];
    self.chatListManager = [HDChatListManager shareManager];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatListRed:) name:@"chatlistRed" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateMessage:) name:@"updateMessage" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(removeListRed:) name:@"removeListRed" object:nil];
    
    
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    self.navigationController.navigationBar.hidden = NO;
    if (self.chatSign.integerValue == 0) {
            //第一次进入聊天列表
            self.chatSign = @"1";
            [[NSUserDefaults standardUserDefaults] setObject:@"1" forKey:@"firstChat"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            [self.tableView.nothingRefreshView show];
            [self resutlChatList];
        }else
        {
            if (![self.chatListManager fmdbIncludeChatList] || ![self.chatListManager fmdbIncludeData]) {
                [self.tableView.nothingRefreshView show];
                [self resutlChatList];
            }else{
                
                if ([self.chatListManager shouldRefreshChatListData]) {
                    [self resutlChatList];
                }else
                {
                    self.chatListResutl.dataSourceArray = [self.chatListManager arrayFromFmdb];
                    [self.tableView reloadData];
                }
            }
     
        }
    
    if (self.tempPmids.count == 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"removeRed" object:nil];
    }

}
//添加小红点
-(void)removeListRed:(NSNotification*)info
{
    [self.tempPmids removeAllObjects];
    self.chatListResutl.dataSourceArray = [self.chatListManager arrayFromFmdb];
    [self.tableView reloadData];
    
}
-(void)chatListRed:(NSNotification *)info
{
    NSDictionary *pmidDictionary = [info userInfo];
//    DLog(@"pmids = %@",pmids);
    self.tempPmids = [pmidDictionary objectForKey:@"tempPmid"];
    self.chatListResutl.dataSourceArray = [self.chatListManager arrayFromFmdb];
    [self.tableView reloadData];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"removeRedPoint" object:self];

    
}
-(void)updateMessage:(NSNotification*)info
{
    self.chatListResutl.dataSourceArray = [self.chatListManager arrayFromFmdb];
    [self.tableView reloadData];
}



#pragma mark - 刷新
- (void)refreshData
{
     [self.chatListManager loadChatListData:self.chatListResutl Refresh:@"1"];
}


#pragma mark - 发送请求
-(void)resutlChatList
{
    [self.chatListManager loadChatListData:self.chatListResutl Refresh:@"0"];
    
}

#pragma mark - 数据处理
-(void)chatListLoadData:(HDChatListResult*)rt
{
    [self.tableView endRefreshingAll];
    
    if (rt.success) {
        [self.tableView.nothingRefreshView remove];
        
        self.chatListResutl.dataSourceArray = [self.chatListManager arrayFromFmdb];
        [self.tableView reloadData];
        
        if (self.chatListResutl.dataSourceArray.count == 0) {
            
            CGFloat width = UBO_WINDOW.width - 24;
            UILabel * centerLab = [[UILabel alloc]initWithFrame:CGRectOf([self.view.ubo fx:UB_1_2 ox:-width/2 fy:UB_1_2 oy:-16], [self.view.ubo ow:width oh:32])];
            centerLab.text = @"暂时没有联系人";
            [centerLab setTextAlignment:NSTextAlignmentCenter];
            [centerLab setFont:[UIFont systemFontOfSize:15]];
            [self.view addSubview:centerLab];
            
        }
        
    }else if(rt.failure){
        [self.tableView.nothingRefreshView requestAgain];
    }

}

#pragma mark - tableView代理
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.chatListResutl.dataSourceArray.count;
//    return 13;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellIdentifier = @"cellIdentifier";
    HDChatListCell * cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:cellIdentifier];
    if (cell == nil) {
        cell = [[HDChatListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier userId:[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    cell.delegate = self;
    HDChatListModel * model = self.chatListResutl.dataSourceArray[indexPath.row];
    if (model.delSign.integerValue == 000) {
        [cell cellWithModel:model withTempPmid:self.tempPmids];
    }
    
    cell.backgroundView = nil;

    return cell;


}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (indexPath.row <= self.tempPmids.count-1) {
        if (self.tempPmids.count != 0) {
            [self.tempPmids removeObjectAtIndex:indexPath.row];
        }
    }

    HDChatListCell *cell = (HDChatListCell*)[tableView cellForRowAtIndexPath:indexPath];
    [cell.redPoint removeFromSuperview];
    NSString * content = [NSString stringWithFormat:@"%@回复了您的帖子",cell.name.text];
    if ([cell.lastTalk.text isEqualToString:content]) {
        HDChatReply * reply = [[HDChatReply alloc]init];
        [self.navigationController pushViewController:reply animated:YES];
    }else
    {
        HDChatListModel * model = self.chatListResutl.dataSourceArray[indexPath.row];
        HDChatOBO * chatOBO = [[HDChatOBO alloc]init];
        chatOBO.chat_people_face = model.face;
        chatOBO.chat_people_name = model.name;
        chatOBO.chat_people_uid = model.uid;
        chatOBO.chat_people_pmid = model.pmid;
        [self.navigationController pushViewController:chatOBO animated:YES];
    }

}

//先要设Cell可编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

//定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

//进入编辑模式，按下出现的编辑按钮后
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle==UITableViewCellEditingStyleDelete) {
        //        获取选中删除行索引值
        NSInteger row = [indexPath row];
        NSString * pmid = [NSString string];
        HDChatListModel * model = [self.chatListResutl.dataSourceArray objectAtIndex:row];
        //        删除单元格的某一行时，在用动画效果实现删除过程
        if (model.uid.integerValue == [[[NSUserDefaults standardUserDefaults]objectForKey:@"uid"]integerValue]) {
            pmid = model.fuid;
        }else
        {
            pmid = model.uid;
        }
        [self.chatListManager updataAndDeleteToDB:pmid];
        //        通过获取的索引值删除数组中的值
        [self.chatListResutl.dataSourceArray removeObjectAtIndex:row];
        //删除数据库中得数据
        [self.chatListManager deleteChatListCell:self.chatListResutl ChatPmid:model.pmid];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];


    }
    
    
}


-(void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath
{
     [[NSNotificationCenter defaultCenter]postNotificationName:@"isAreadyRed" object:self];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"removeCellRed" object:nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:@"removePeoRedPoint" object:nil];

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UF(132);
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return UF(0.3);
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return UF(0.5);
}



-(void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}
@end





